package com.fire.chat.aspect;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fire.chat.annotation.CheckPermissions;
import com.fire.chat.cache.AuthorityCacheStrategy;
import com.fire.chat.entity.admin.bo.AdminLoginInfo;
import com.fire.chat.enums.result.AdminResultEnum;
import com.fire.chat.exception.BusinessException;
import com.fire.chat.utils.common.AdminLoginUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import java.lang.reflect.Method;
import java.util.Optional;

/**
 * @program: hxzq
 * @description: 角色权限校验切面
 * @author: xjr
 * @create: 2020-11-04 14:11
 **/
@Aspect
@Slf4j
@Order(99)
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class AuthorityAspect {



    private final AuthorityCacheStrategy cacheStrategy;

    /**
     *方法级别的切点
     */
    private static  final String AUTH_POINTCUT_METHOD="@annotation(com.fire.chat.annotation.CheckPermissions)";




    @Pointcut(AUTH_POINTCUT_METHOD)
    public void methodPoint(){

    }



    @Before("methodPoint()")
    public void methodBefore(JoinPoint joinPoint) throws Exception{
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        CheckPermissions check = method.getAnnotation(CheckPermissions.class);
        String menuCode=check.value();
        log.info("----------------------用户角色权限校验-----------------------------------");
        if (StringUtils.isNotBlank(menuCode)){
            Long uid = Optional.ofNullable(AdminLoginUtil.get()).map(AdminLoginInfo::getUserId).orElseThrow(() -> new BusinessException(AdminResultEnum.TOKEN_NOT_NULL));
            boolean flag = cacheStrategy.checkPermission(menuCode, uid.toString());
            if (!flag){
                throw new BusinessException(403,"无权限操作此资源");
            }
        }

    }




}
